<template>
  <div>
    <!--面包屑导航区-->
    <my-bread level1="商品管理" level2="分类参数"></my-bread>
    <el-card>
      <!--提示-->
      <el-alert title="只允许为第三级分类设置参数" type="info" show-icon></el-alert>
      <el-form>
        <el-form-item label="商品名称">
            <!--级联选择器-->
            <el-cascader
            :options="options"
            v-model="selectedOptions"
            :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' }"
            @change="handleChange" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <!--tab标签页-->
      <el-tabs v-model="active" @tab-click="handleClick">

        <el-tab-pane label="动态参数" name="1">
          <el-button type="danger">设置动态参数</el-button>
          <el-table :data="dyParamsArr" style="width: 100%">
            <el-table-column type="expand" label="#">
              <template slot-scope="scope">
                <!--动态可编辑的tag标签-->
                <el-tag
                  :key="tag"
                  v-for="tag in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row,tag)">
                  {{tag}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态参数" name="2">
          <el-table :data="staticParamsArr" style="width: 100%">
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="商品名称" prop="attr_name"></el-table-column>
            <el-table-column label="商品名称" prop="attr_vals"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器绑定的数据
      selectedOptions: [],
      options: [],
      active: '1',
      // 动态参数数组
      dyParamsArr: [],
      // el-tag控制输入框和按钮的显示隐藏
      inputVisible: false,
      inputValue: '',
      // 静态参数数组
      staticParamsArr: []
    }
  },
  created() {
    this.getGoodsCat()
  },
  methods: {
    // 级联选择器绑定的方法
    async handleChange() {
      if (this.selectedOptions.length === 3) {
        // 获取动态参数数据 id -> 三级商品分类id
        const { data: res } = await this.$http.get(`categories/${this.selectedOptions[2]}/attributes?sel=many`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
        this.dyParamsArr = res.data
        this.dyParamsArr.forEach(item => {
          // 并不是所有的三级分类都有动态参数 ''->不是[]->v-for报错
          item.attr_vals =
          item.attr_vals.length === 0 ? [] : item.attr_vals.trim().split(',')
        })
        this.active = '1'
      }
    },
    async getGoodsCat() {
      const { data: res } = await this.$http.get('categories?type=3')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据列表失败')
      // console.log(res)
      this.options = res.data
    },
    // tab切换时触发
    async handleClick() {
      if (this.active === '2') {
        if (this.selectedOptions.length === 3) {
          // 获取静态参数数据
          const { data: res } = await this.$http.get(`categories/${this.selectedOptions[2]}/attributes?sel=only`)
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error('获取静态参数失败')
          this.staticParamsArr = res.data
        }
      }
    },
    // 动态编辑标签相关方法 - ×按钮删除
    async handleClose(dyparam, tag) {
      dyparam.attr_vals.splice(dyparam.attr_vals.indexOf(tag), 1)
      // 发送请求 1.7.5. 编辑提交参数 categories/:id/attributes/:attrId
      // | attr_name | 参数名称                                   | 不能为空              |
      // | attr_sel  | [only,many]                                | 不能为空              |
      // | attr_vals | 如果是 many 就需要填写值的选项，以逗号分隔 | 【可选参数】          |
      let putData = {
        attr_name: dyparam.attr_name,
        attr_sel: 'many',
        attr_vals: dyparam.attr_vals.join(',')
      }
      const { data: res } = await this.$http.put(`categories/${this.selectedOptions[2]}/attributes/${dyparam.attr_id}`, putData)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
    },
    // 点击+ New Tag按钮
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 回车or 失去焦点
    async handleInputConfirm(dyparam) {
      let inputValue = this.inputValue
      if (inputValue) {
        dyparam.attr_vals.push(inputValue)
        // 发送请求
        let putData = {
          attr_name: dyparam.attr_name,
          attr_sel: 'many',
          attr_vals: dyparam.attr_vals.join(',')
        }
        const { data: res } = await this.$http.put(`categories/${this.selectedOptions[2]}/attributes/${dyparam.attr_id}`, putData)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
    margin-top: 15px;
}

.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
